/* eslint-disable */
import { ref, computed } from 'vue'
import CryptoJS from 'crypto-js'

const APPID = import.meta.env.VITE_APP_XUNFEI_APPID
const API_KEY = import.meta.env.VITE_APP_XUNFEI_APIKEY

function getWebSocketUrl() {
  // 请求地址根据语种不同变化
  const url = 'wss://rtasr.xfyun.cn/v1/ws'
  const appId = APPID
  const secretKey = API_KEY
  const ts = Math.floor(new Date().getTime() / 1000)
  const signa = window.hex_md5(appId + ts)
  const signatureSha = window.CryptoJSNew.HmacSHA1(signa, secretKey)
  let signature = CryptoJS.enc.Base64.stringify(signatureSha)
  signature = encodeURIComponent(signature)
  return `${url}?appid=${appId}&ts=${ts}&signa=${signature}`
}

export const STATUS = {
  UNDEFINED: 'UNDEFINED',
  CONNECTING: 'CONNECTING',
  OPEN: 'OPEN',
  CLOSING: 'CLOSING',
  CLOSED: 'CLOSED'
}

const useXf = () => {
  const status = ref(STATUS.UNDEFINED)
  const resultText = ref('')
  const resultTextTemp = ref('')
  const recordStart = ref(false)

  const displayText = computed(() => {
    return resultText.value + resultTextTemp.value
  })
  let iatWS

  const changeStatus = stat => {
    status.value = stat
    if (stat === STATUS.CONNECTING) {
      resultText.value = ''
      resultTextTemp.value = ''
      displayText.value = ''
    }
  }

  const recorder = new window.RecorderManager(`${import.meta.env.VITE_APP_CONTEXT_PATH}/xf/`)
  recorder.onStart = () => {
    changeStatus('OPEN')
  }

  const renderResult = (resultData: string) => {
    const jsonData = JSON.parse(resultData)
    if (jsonData.action == 'started') {
      // 握手成功
      console.log('握手成功')
      recordStart.value = true
    } else if (jsonData.action == 'result') {
      const data = JSON.parse(jsonData.data)
      console.log(data)
      // 转写结果
      resultTextTemp.value = ''
      data.cn.st.rt.forEach(j => {
        j.ws.forEach(k => {
          k.cw.forEach(l => {
            resultTextTemp.value += l.w
          })
        })
      })
      if (data.cn.st.type == 0) {
        // 【最终】识别结果：
        resultText.value += resultTextTemp.value
        resultTextTemp.value = ''
      }
    } else if (jsonData.action == 'error') {
      // 连接发生错误
      console.log('出错了:', jsonData)
    }
  }

  const connectWebsocket = () => {
    const websocketUrl = getWebSocketUrl()
    if ('WebSocket' in window) {
      iatWS = new WebSocket(websocketUrl)
    } else if ('MozWebSocket' in window) {
      iatWS = new MozWebSocket(websocketUrl)
    } else {
      alert('浏览器不支持WebSocket')
      return
    }

    changeStatus(STATUS.CONNECTING)
    iatWS.onopen = e => {
      console.log('[xf] onopen')
      // 开始录音
      recorder.start({
        sampleRate: 16000,
        frameSize: 1280
      })
    }
    iatWS.onmessage = e => {
      renderResult(e.data)
    }
    iatWS.onerror = e => {
      console.error(e)
      recorder.stop()
      changeStatus('CLOSED')
    }
    iatWS.onclose = e => {
      recorder.stop()
      changeStatus('CLOSED')
    }

    recorder.onFrameRecorded = ({ isLastFrame, frameBuffer }) => {
      if (iatWS.readyState === iatWS.OPEN) {
        iatWS.send(new Int8Array(frameBuffer))
        if (isLastFrame) {
          iatWS.send('{"end": true}')
          changeStatus('CLOSING')
        }
      }
    }
  }

  const startRecord = () => {
    if (status.value == STATUS.UNDEFINED || status.value == STATUS.CLOSED) {
      connectWebsocket()
    }
  }

  const stopRecord = () => {
    if (status.value == STATUS.CONNECTING || status.value == STATUS.OPEN) {
      recordStart.value = false
      console.log('[xf] stop recorder')
      recorder.stop()
      resultText.value = ''
      resultTextTemp.value = ''
    }
  }

  return {
    status,
    recordStart,
    displayText,
    startRecord,
    stopRecord
  }
}

export default useXf
